# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json

from django.contrib.auth.decorators import login_required
from django.db.models import Max
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from wenlincms.utils.views import render

from wlmodels.codes.models import ELNic, ELRegion
from wlmodels.dataplus.models import ELStatisticsEnt, ELStatisticsEntMonth, ELStatisticsTax, ELStatisticsHG
from wlviews.saas.fee import customer_verify_fee, noauth_redirct_url


@never_cache
# @login_required
@csrf_exempt
def statistics_chain(request):
    # if customer_verify_fee(request, saas_pindao="40"):
    #     return HttpResponseRedirect(noauth_redirct_url)

    # POST方法，返回json数据
    if request.method == "POST":
        result_tmp = {"regionbar": {}, "nicbar": {}, "total": {}}
        region_id = request.POST['region'] if 'region' in request.POST else ''
        nic_id = request.POST['nic'] if 'nic' in request.POST else ''
        entstatus = request.POST['ENTSTATUS'] if 'ENTSTATUS' in request.POST else ''
        tmonth = request.POST['tmonth'] if 'tmonth' in request.POST else ''
        if tmonth:
            tmonth = int(tmonth)
        else:
            tmonth_max = ELStatisticsEnt.objects.all().aggregate(Max('tmonth'))
            if tmonth_max['tmonth__max']:
                tmonth = int(tmonth_max['tmonth__max'])
            else:
                tmonth = 1609
        ishome = request.POST['ishome'] if 'ishome' in request.POST else ''
        # 进行计费
        # if not ishome and customer_verify_fee(request, saas_pindao="40", saas_item="70",
        #                                       tkey=json.dumps({"page": "chain", "region": region_id, "nic": nic_id})):
        #     return HttpResponse(json.dumps({"noauth": "1"}), content_type="application/json")

        lookup_region = {"tmonth": tmonth, "region_id_id__in": get_child_nodes("region", region_id), "nic_id_id": nic_id, "ENTSTATUS": entstatus}
        objs_region = ELStatisticsEnt.objects.filter(**lookup_region)
        for obj in objs_region:
            the_name = get_names_from_code("region", obj.region_id_id)
            if the_name not in result_tmp["regionbar"]:
                result_tmp["regionbar"][the_name] = {}
            result_tmp["regionbar"][the_name][obj.get_companytype_display()] = obj.count

        lookup_nic = {"tmonth": tmonth, "region_id_id": region_id, "nic_id_id__in": get_child_nodes("nic", nic_id), "ENTSTATUS": entstatus}
        objs_nic = ELStatisticsEnt.objects.filter(**lookup_nic)
        for obj in objs_nic:
            the_name = get_names_from_code("nic", obj.nic_id_id)
            if the_name not in result_tmp["nicbar"]:
                result_tmp["nicbar"][the_name] = {}
            result_tmp["nicbar"][the_name][obj.get_companytype_display()] = obj.count

        # 重新排序并组织为highchart所需格式
        result = {"regionbar": {"title": [], "企业": [], "个体户": []}, "nicbar": {"title": [], "企业": [], "个体户": []}, "total": {}}
        region_list = [[k, v] for k, v in result_tmp["regionbar"].iteritems()]
        for y in sorted(region_list, key=lambda x: x[1]["企业"], reverse=True):
            result["regionbar"]["title"].append(y[0])
            result["regionbar"]["企业"].append(result_tmp["regionbar"][y[0]]["企业"])
            result["regionbar"]["个体户"].append(result_tmp["regionbar"][y[0]]["个体户"])
        nic_list = [[k, v] for k, v in result_tmp["nicbar"].iteritems()]
        for y in sorted(nic_list, key=lambda x: x[1]["企业"], reverse=True):
            result["nicbar"]["title"].append(y[0])
            result["nicbar"]["企业"].append(result_tmp["nicbar"][y[0]]["企业"])
            result["nicbar"]["个体户"].append(result_tmp["nicbar"][y[0]]["个体户"])

        if not ishome:
            lookup_total = {"tmonth": tmonth, "region_id_id": region_id, "nic_id_id": nic_id, "ENTSTATUS": entstatus}
            objs_total = ELStatisticsEnt.objects.filter(**lookup_total)
            for obj in objs_total:
                result["total"][obj.get_companytype_display()] = obj.count
        return HttpResponse(json.dumps(result), content_type="application/json")
    return render(request, "saas/statistics/statistics_chain.html", {})


@never_cache
@login_required
@csrf_exempt
def statistics_entmonth(request):
    if customer_verify_fee(request, saas_pindao="40"):
        return HttpResponseRedirect(noauth_redirct_url)

    if request.method == "POST":
        result, tmonth_exist = {"region": {"title": [], "新增企业数": [], "注销企业数": [], "吊销企业数": [], "新增个体数": [], "注销个体数": [], "吊销个体数": []},
                                "industry": {"title": [], "新增企业数": [], "注销企业数": [], "吊销企业数": [], "新增个体数": [], "注销个体数": [], "吊销个体数": []},
                                "bar": []}, []
        region_id = request.POST['region'] if 'region' in request.POST else ''
        nic_id = request.POST['nic'] if 'nic' in request.POST else ''
        tmonth = request.POST['tmonth'] if 'tmonth' in request.POST else ''
        tmonth = get_month_from_tmonth(str(tmonth), reverse=True) if tmonth else 1607
        # 进行计费
        if customer_verify_fee(request, saas_pindao="40", saas_item="70",
                               tkey=json.dumps({"page": "entmonth", "region": region_id, "nic": nic_id})):
            return HttpResponse(json.dumps({"noauth": "1"}), content_type="application/json")

        lookup_region = {"tmonth": tmonth, "region_id_id__in": get_child_nodes("region", region_id), "nic_id_id": nic_id}
        objs_region = ELStatisticsEntMonth.objects.filter(**lookup_region)
        for obj in objs_region:
            the_name = get_names_from_code("region", obj.region_id_id)
            result["region"]["title"].append(the_name)
            result["region"]["新增企业数"].append(obj.newent)
            result["region"]["注销企业数"].append(obj.cancelent)
            result["region"]["吊销企业数"].append(obj.revokeent)
            result["region"]["新增个体数"].append(obj.newgeti)
            result["region"]["注销个体数"].append(obj.cancelgeti)
            result["region"]["吊销个体数"].append(obj.revokegeti)

        lookup_nic = {"tmonth": tmonth, "nic_id_id__in": get_child_nodes("nic", nic_id), "region_id_id": region_id}
        objs_nic = ELStatisticsEntMonth.objects.filter(**lookup_nic)
        for obj in objs_nic:
            the_name = get_names_from_code("nic", obj.nic_id_id)
            result["industry"]["title"].append(the_name)
            result["industry"]["新增企业数"].append(obj.newent)
            result["industry"]["注销企业数"].append(obj.cancelent)
            result["industry"]["吊销企业数"].append(obj.revokeent)
            result["industry"]["新增个体数"].append(obj.newgeti)
            result["industry"]["注销个体数"].append(obj.cancelgeti)
            result["industry"]["吊销个体数"].append(obj.revokegeti)

        lookup_bar = {"region_id_id": region_id, "nic_id_id": nic_id}
        objs_bar = ELStatisticsEntMonth.objects.filter(**lookup_bar).order_by("-tmonth")
        for obj in objs_bar:
            if obj.tmonth not in tmonth_exist:
                tmonth_exist.append(obj.tmonth)
                result["bar"].append([get_month_from_tmonth(obj.tmonth), obj.newent if obj.newent else 0, obj.cancelent if obj.cancelent else 0,
                                      obj.revokeent if obj.revokeent else 0, obj.newgeti if obj.newgeti else 0,
                                      obj.cancelgeti if obj.cancelgeti else 0, obj.revokegeti if obj.revokegeti else 0])
        return HttpResponse(json.dumps(result), content_type="application/json")
    return render(request, "saas/statistics/statistics_entmonth.html", {})


@never_cache
@login_required
@csrf_exempt
def statistics_tax(request):
    if customer_verify_fee(request, saas_pindao="40"):
        return HttpResponseRedirect(noauth_redirct_url)

    if request.method == "POST":
        result, tyear_exist = {"region": {"title": [], "总营收": [], "平均营收": [], "总利润": [], "平均利润": []},
                               "industry": {"title": [], "总营收": [], "平均营收": [], "总利润": [], "平均利润": []}, "bar": []}, []
        region_id = request.POST['region'] if 'region' in request.POST else ''
        nic_id = request.POST['nic'] if 'nic' in request.POST else ''
        tyear = request.POST['tyear'] if 'tyear' in request.POST else ''
        tyear = int(tyear) if tyear else 2014
        # 进行计费
        if customer_verify_fee(request, saas_pindao="40", saas_item="70",
                               tkey=json.dumps({"page": "tax", "region": region_id, "nic": nic_id})):
            return HttpResponse(json.dumps({"noauth": "1"}), content_type="application/json")

        lookup_region = {"year": tyear, "region_id_id__in": get_child_nodes("region", region_id), "nic_id_id": nic_id}
        objs_region = ELStatisticsTax.objects.filter(**lookup_region)
        for obj in objs_region:
            the_name = get_names_from_code("region", obj.region_id_id)
            result["region"]["title"].append(the_name)
            result["region"]["总营收"].append(obj.revenue_total / 10000 if obj.revenue_total else 0)
            result["region"]["平均营收"].append(obj.revenue)
            result["region"]["总利润"].append(obj.total_profit_total / 10000 if obj.total_profit_total  else 0)
            result["region"]["平均利润"].append(obj.total_profit)

        lookup_nic = {"year": tyear, "nic_id_id__in": get_child_nodes("nic", nic_id), "region_id_id": region_id}
        objs_nic = ELStatisticsTax.objects.filter(**lookup_nic)
        for obj in objs_nic:
            the_name = get_names_from_code("nic", obj.nic_id_id)
            result["industry"]["title"].append(the_name)
            result["industry"]["总营收"].append(obj.revenue_total / 10000 if obj.revenue_total else 0)
            result["industry"]["平均营收"].append(obj.revenue)
            result["industry"]["总利润"].append(obj.total_profit_total / 10000 if obj.total_profit_total  else 0)
            result["industry"]["平均利润"].append(obj.total_profit)

        lookup_bar = {"region_id_id": region_id, "nic_id_id": nic_id}
        objs_bar = ELStatisticsTax.objects.filter(**lookup_bar).order_by("-year")
        for obj in objs_bar:
            if obj.year not in tyear_exist:
                tyear_exist.append(obj.year)
                result["bar"].append([obj.year, obj.revenue_total / 10000 if obj.revenue_total else 0, obj.revenue if obj.revenue else 0,
                                      obj.total_profit_total / 10000 if obj.total_profit_total else 0, obj.total_profit if obj.total_profit else 0])
        return HttpResponse(json.dumps(result), content_type="application/json")
    return render(request, "saas/statistics/statistics_tax.html", {})


@never_cache
@login_required
@csrf_exempt
def statistics_hg(request):
    if customer_verify_fee(request, saas_pindao="40"):
        return HttpResponseRedirect(noauth_redirct_url)

    if request.method == "POST":
        result, tmonth_exist = {"region": {"title": [], "进口总额": [], "出口总额": []},
                                "industry": {"title": [], "进口总额": [], "出口总额": []}, "bar": []}, []
        region_id = request.POST['region'] if 'region' in request.POST else ''
        nic_id = request.POST['nic'] if 'nic' in request.POST else ''
        tmonth = request.POST['tmonth'] if 'tmonth' in request.POST else ''
        tmonth = get_month_from_tmonth(str(tmonth), reverse=True) if tmonth else 1607
        # 进行计费
        if customer_verify_fee(request, saas_pindao="40", saas_item="70",
                               tkey=json.dumps({"page": "hg", "region": region_id, "nic": nic_id})):
            return HttpResponse(json.dumps({"noauth": "1"}), content_type="application/json")

        lookup_region = {"tmonth": tmonth, "region_id_id__in": get_child_nodes("region", region_id), "nic_id_id": nic_id}
        objs_region = ELStatisticsHG.objects.filter(**lookup_region)
        for obj in objs_region:
            the_name = get_names_from_code("region", obj.region_id_id)
            result["region"]["title"].append(the_name)
            result["region"]["进口总额"].append(obj.timport)
            result["region"]["出口总额"].append(obj.texport)

        lookup_nic = {"tmonth": tmonth, "nic_id_id__in": get_child_nodes("nic", nic_id), "region_id_id": region_id}
        objs_nic = ELStatisticsHG.objects.filter(**lookup_nic)
        for obj in objs_nic:
            the_name = get_names_from_code("nic", obj.nic_id_id)
            result["industry"]["title"].append(the_name)
            result["industry"]["进口总额"].append(obj.timport)
            result["industry"]["出口总额"].append(obj.texport)

        lookup_bar = {"region_id_id": region_id, "nic_id_id": nic_id}
        objs_bar = ELStatisticsHG.objects.filter(**lookup_bar).order_by("-tmonth")
        for obj in objs_bar:
            if obj.tmonth not in tmonth_exist:
                tmonth_exist.append(obj.tmonth)
                result["bar"].append([get_month_from_tmonth(obj.tmonth), obj.timport if obj.timport else 0,
                                      obj.texport if obj.texport else 0])
        return HttpResponse(json.dumps(result), content_type="application/json")
    return render(request, "saas/statistics/statistics_hg.html", {})


# 地区和行业分类等的树表控件所需json
@csrf_exempt
@never_cache
@login_required
def statistics_loadnode(request):
    result = []
    method = request.GET.get("method")
    code = request.POST['code'] if 'code' in request.POST else ''
    queryset = get_child_nodes(method, code, contenttype="queryset")
    for obj in queryset:
        result.append({"id": obj.id, "code": obj.code, "parent": code, "fulltitle": obj.fulltitle,
                       "level": obj.level, "name": obj.name, "expanded": False, "isLeaf": True if code else False})
    return HttpResponse(json.dumps(result))


# get，返回企业榜单
@never_cache
@login_required
@csrf_exempt
def statistics_bangdan(request):
    sortfield = request.GET.get("sortfiled", None)
    sortfield = sortfield if sortfield else "revenue"
    context = {"sortfield": sortfield}
    return render(request, "saas/statistics/statistics_bangdan.html", context)


# get，返回各个指标的直方图
@never_cache
@login_required
@csrf_exempt
def statistics_histogram(request):
    if customer_verify_fee(request, saas_pindao="40"):
        return HttpResponseRedirect(noauth_redirct_url)

    if request.method == "POST":
        region_id = request.POST['region'] if 'region' in request.POST else ""
        nic_id = request.POST['nic'] if 'nic' in request.POST else ""
        tmonth = request.POST['tmonth'] if 'tmonth' in request.POST else ''
        if tmonth:
            tmonth = int(tmonth)
        else:
            tmonth_max = ELStatisticsEnt.objects.all().aggregate(Max('tmonth'))
            if tmonth_max['tmonth__max']:
                tmonth = int(tmonth_max['tmonth__max'])
            else:
                tmonth = 1609
        # 进行计费
        if customer_verify_fee(request, saas_pindao="40", saas_item="70",
                               tkey=json.dumps({"page": "entage", "region": region_id, "nic": nic_id})):
            return HttpResponse(json.dumps({"noauth": "1"}), content_type="application/json")

        result = {"ent": "[[0, 0]]", "geti": "[[0, 0]]"}
        lookups_ent = {"tmonth": tmonth, "region_id_id": region_id, "nic_id_id": nic_id, "ENTSTATUS": "1", "companytype": 0}
        lookups_geti = {"tmonth": tmonth, "region_id_id": region_id, "nic_id_id": nic_id, "ENTSTATUS": "1", "companytype": 1}
        obj_ent = ELStatisticsEnt.objects.filter(**lookups_ent).first()
        obj_geti = ELStatisticsEnt.objects.filter(**lookups_geti).first()
        if obj_ent and obj_ent.companyage:
            result["ent"] = "%s" % obj_ent.companyage
        if obj_geti and obj_geti.companyage:
            result["geti"] = "%s" % obj_geti.companyage
        return HttpResponse(json.dumps(result), content_type="application/json")
    return render(request, "saas/statistics/statistics_histogram.html", {})


# 获取选定的地区或行业的下级，最多到2级
def get_child_nodes(method, code, contenttype="codelist"):
    if method not in ["nic", "region", ]:
        return [code]
    if not code:
        if method == "region":
            queryset = ELRegion.objects.filter(parent=code)
        else:
            queryset = ELNic.objects.filter(parent=code)
    else:
        if method == "region" and code in ['110000', "120000", "310000", "500000"]:
            queryset = ELRegion.objects.filter(code__istartswith=code[:2], level="3")
        elif method == "region":
            queryset = ELRegion.objects.filter(parent=code, level="2")
        else:
            queryset = ELNic.objects.filter(parent=code, level="2")
    if contenttype == "queryset":
        return queryset.order_by('code')
    else:
        if queryset.count():
            return list(queryset.order_by('code').values_list('code', flat=True))
        else:
            return [code]


# 获取给定code对应的名称
def get_names_from_code(method, code):
    if method == "nic" and code:
        the_obj = ELNic.objects.filter(code=code).first()
        if the_obj:
            return the_obj.name
    elif method == "region" and code:
        the_obj = ELRegion.objects.filter(code=code).first()
        if the_obj:
            return the_obj.name
    return ""


# 获取给定tmonth对应的月份
def get_month_from_tmonth(tmonth, reverse=False):
    if not reverse:
        if isinstance(tmonth, int):
            if 101 <= tmonth <= 912:
                return "200" + str(tmonth)[0] + "-" + str(tmonth)[1:]
            if 1001 <= tmonth <= 2012:
                return "20" + str(tmonth)[:2] + "-" + str(tmonth)[2:]
        return "2000-01"
    else:
        try:
            return int(tmonth.replace("-", "")) - 200000
        except Exception:
            return 1601
